package com.ctos.filter;

import com.alibaba.fastjson.JSON;
import com.ctos.common.BaseContext;
import com.ctos.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns ="/*")
@Slf4j
public class LoginFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();//获取本次请求的路径
        //放行路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/common/**",
                //以下为swagger的接口生成网址
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        boolean check = check(urls, requestURI);
        //判断本次请求是否需要处理
        if (check){
            filterChain.doFilter(request, response);
            return;
        }

        //判断是否以登录
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (userId!=null){
            //在该线程中存入当前登录id
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }


        if (request.getSession().getAttribute("user") != null){
            //在该线程中存入当前登录id
            Long user = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(user);
            filterChain.doFilter(request, response);
            return;
        }

        //前端也写了拦截器直接回写数据即可
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));

    }

    /**
     * 路径匹配
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }


}
